const   express = require('express'),
        router = express.Router(),
        util = require("../util/util"),
        category = require("../model/category");
/**
 * @function 增加栏目
 * @author Wayne
 * @date 2018
 * @param catid,catname,parentid,cattype,caturl,,keyword,catcomment,sortid,showflag
 */
router.post('/add', (req, res) => {
    const newObj = new category(req.body);
    let catname = req.body.catname;
    let catid = util.randomString(8);
    newObj.catid=catid;
  let params = {
      catname: catname,
  }
    category.find(params, (err,results)=> {
        if(err){
            res.send(util.reObj(-1,'添加分类失败',err))
        }else {
            if(results.length>0){
                res.send(util.reObj(-2,'该栏目已存在'))
            }else{
                newObj.save( (err, result)=>{
                    if(err){
                        res.send(util.reObj(-1,'添加分类失败'))
                    }else{
                        res.send(util.reObj(0,'添加分类成功',result))
                    }
                })
            }
        }
    })

})

/**
 * @function 修改栏目
 * @author Wayne
 * @date 2018
 * @param catid,catname,cattype,keyword,caturl,catcomment,sortid,showflag
 */
router.post('/edit', (req, res) => {
  let catid = req.body.catid
  let catname = req.body.catname || ''
  let cattype = req.body.cattype || ''
  let keyword = req.body.keyword || ''
  let caturl = req.body.caturl || ''
  let iconclass = req.body.iconclass || ''
  let iconcolor = req.body.iconcolor || ''
  let catcomment = req.body.catcomment || ''
  let sortid = req.body.sortid || ''
  let showflag = req.body.showflag || ''
  let params = {
    catid: catid
  }
  let updateparams = {
    catname: catname,
    cattype: cattype,
    keyword: keyword,
      iconclass:iconclass,
      iconcolor:iconcolor,
    catcomment: catcomment,
    sortid: sortid,
    caturl: caturl,
    showflag: showflag
  }

  //去掉空的属性
    //去掉空的属性
    for (var key of Object.keys(updateparams)) {
        if (!updateparams[key])
            delete updateparams[key]
    }

    category.findOneAndUpdate(params,updateparams,(err,results)=>{
        if(err)
        {
            res.send(util.reObj(-1,'修改失败',err))
        }
        else
        {
            res.send(util.reObj(0,'修改成功',results))
        }
    })


})

/**
 * @function 删除栏目
 * @author Wayne
 * @date 2018
 * @param catid
 */
router.post('/del', (req, res) => {
    let catid = req.body.catid
    let params = {
        catid: catid
    }

    if(catid)
    {
        category.deleteMany(params,(err,result)=>{
            if (err) {
                res.send(util.reObj(-1,'删除失败'))
            }
            else {
                if(result.deletedCount>0)
                {
                    res.send(util.reObj(0,'删除成功'))
                }
                else
                {
                    res.send(util.reObj(0,'删除失败或此记录不存在'))
                }
            }
        })
    }
    else{
        res.send(util.reObj(-1,'catid can not be null'))
    }


})

/**
 * @function 获取栏目数据（下属，递归调用）(前台有同样的接口)
 * @author Wayne
 * @date 2018
 * @param parentid
 */
router.post('/getcatlist', (req, res) => {
  let parentid = req.body.parentid || 'ROOT'
  let params = {}
    category.find(params,null,{sort: {sortid: 1}},function (err,results) {
        if(err)
        {
            res.send(util.reObj(-1,'failed',err))
        }
        else
        {
            if(results.length>0){
                let arr = []
                let serilize_res = JSON.parse(JSON.stringify(results))
                for (i in serilize_res) {
                    arr.push(serilize_res[i]);
                }
                let tree = util.recursion(arr, parentid,'catid');
                res.send(util.reObj(0,'获取成功',tree))
            }
            else
            {
                res.send(util.reObj(-1,'获取失败或记录不存在'))
            }
        }
    })

})

/**
 * @function 根据catid获取栏目信息(前天有同样的接口)
 * @author siwei
 * @date 2018-07-04
 * @param catid
 */
router.post('/getCatbyid', (req, res) => {
  let params = {}
  let catid = req.body.catid
  params.catid = catid

    category.findOne({where: params}).then(record => {
    if (record) {
      res.send(util.reObj(0, '获取栏目信息成功', record))
    } else {
      res.send(util.reObj(-1, '获取栏目信息失败或此记录不存在', {}))
    }
  }).catch(err => {
    res.send(util.reObj(-1, '获取栏目信息失败', err))
  });
})


module.exports = router;
